var request = require("request");
var fs = require("fs");
var moment = require('moment');
const schedule = require('node-schedule')

startJob();

function getImageUrl(){
    return new Promise((resolve,reject)=>{
        request("https://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",(err,response,body)=>{
            if (!err && response.statusCode == 200) { 
                var json =JSON.parse(body);
                let url = 'https://cn.bing.com/'+json.images[0].url.replace("_1920x1080",'_UHD');
                resolve(url);
            }
        })
    })
}

schedule.scheduleJob('*/4 * * *', async function () {
    startJob();
})


async function startJob(){
    let url = await getImageUrl();
    let filename = moment().format("YYYYMMDD")+".jpg"; 　　// 已原网络图片的名称命名本地图片
    request(url).pipe(
        fs.createWriteStream(`./imgs/${filename}`).on('close',err=>{  
            if(err){
                console.log('写入失败',err)
            }
            else
            {
                console.log(filename+' 写入成功');
            }
        })
    )
}
